/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import java.awt.event.KeyEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import resources.local_connection;

/**
 *
 * @author pato
 */
public final class Especiales extends javax.swing.JDialog {

    /**
     * Creates new form Especiales
     */
    int idproducto;
    PreparedStatement ps;
    ResultSet rs;
    String tipo;
    int sucursal;
    DefaultTableModel dtm;
    ArrayList<String> especiales = new ArrayList<String>();//guarda los datos obtenidos de la base de datos

    public Especiales(java.awt.Frame parent, boolean modal, int id, String t, int s) {
        super(parent, modal);
        initComponents();
        JTableHeader th = jTable1.getTableHeader();
        TableColumnModel tcm = th.getColumnModel();
        TableColumn tc = tcm.getColumn(0);
        idproducto = id;
        tipo = t;
        sucursal = s;
        if ("Chip".equals(tipo)) {
            tc.setHeaderValue("ICC");
        } else {
            tc.setHeaderValue("IMEI");
            jTextField1.setDocument(new LimitadorCaracteres());
        }
        super.setTitle("Sucursal " + sucursal);
        th.repaint();
        dtm = (DefaultTableModel) this.jTable1.getModel();
        cargarDatos();
    }

    void cargarDatos() {
        try {
            dtm.setRowCount(0);
            ps = (PreparedStatement) local_connection.getconnect().prepareStatement("Select clave, sucursal, fecha from especiales where id_producto = ?");
            ps.setInt(1, idproducto);
            rs = ps.executeQuery();
            ArrayList<Object[]> data = new ArrayList<>();

            while (rs.next()) {
                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                especiales.add(rs.getString(1));
                data.add(rows);
            }

            for (Object[] data1 : data) {
                dtm.addRow(data1);
            }
        } catch (SQLException ex) {
            Almacen.logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        Quitar = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextField1 = new javax.swing.JTextField();
        agregar = new javax.swing.JButton();

        Quitar.setText("Quitar");
        Quitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                QuitarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(Quitar);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Clave", "Sucursal", "Fecha"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setComponentPopupMenu(jPopupMenu1);
        jScrollPane1.setViewportView(jTable1);

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        agregar.setText("Agregar");
        agregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                agregarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(agregar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(agregar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1KeyPressed

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            agregar.doClick();
        }

// TODO add your handling code here:
    }//GEN-LAST:event_jTextField1KeyReleased
    class LimitadorCaracteres extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!Character.isDigit(arg1.charAt(i))) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    private void agregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarActionPerformed
        String cadena = jTextField1.getText();
        int longitud = cadena.length();
        boolean pasa = true;
        if (tipo.equals("Chip")) {
            if ((longitud > 20) || (longitud < 20)) {
                JOptionPane.showMessageDialog(this, "La longitud del ICC tiene que ser de 20");
                pasa = false;
            }
        } else if ((longitud > 15) || (longitud < 15)) {
            JOptionPane.showMessageDialog(this, "La longitud del IMEI tiene que ser de 15");
            pasa = false;
        }
        if (especiales.contains(cadena)) {
            JOptionPane.showMessageDialog(this, "Esta clave ya esta repetida");
            pasa = false;
        }
        if (pasa) {
            try {
                ps = local_connection.getconnect().prepareStatement("Insert into especiales(id_producto,clave,sucursal,tipo) values(?,?,?,?)");
                ps.setInt(1, idproducto);
                ps.setString(2, cadena);
                ps.setInt(3, sucursal);
                ps.setString(4, tipo);
                ps.execute();
                cargarDatos();
                jTextField1.setText("");
            } catch (SQLException ex) {
                Almacen.logger.log(Level.SEVERE, null, ex);
            }
        }

// TODO add your handling code here:
    }//GEN-LAST:event_agregarActionPerformed

    private void QuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_QuitarActionPerformed
        int row = jTable1.getSelectedRow();
        if (row != -1) {
            row = jTable1.convertRowIndexToModel(row);
            try {
                ps = local_connection.getconnect().prepareStatement("delete from especiales where clave = ?");
                ps.setString(1, String.valueOf(dtm.getValueAt(row, 0)));
                ps.execute();
                cargarDatos();
            } catch (SQLException ex) {
                Almacen.logger.log(Level.SEVERE, null, ex);
            }

        }

// TODO add your handling code here:
    }//GEN-LAST:event_QuitarActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem Quitar;
    private javax.swing.JButton agregar;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
